/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2009.
 *
 * Licensed under the Aduna BSD-style license.
 */

package edu.tju.commons.collections.iterators;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An iterator that limits the amount of elements that it returns from an
 * underlying iterator to a fixed amount. This class returns the first
 * <tt>limit</tt> elements from the underlying iterator and drops the rest.
 */
public class LimitIterator<E> extends IteratorWrapper<E> {

	/**
	 * The amount of elements to return.
	 */
	private final int limit;

	/**
	 * The number of elements that have been returned so far.
	 */
	private int returnCount;

	/**
	 * Creates a new LimitIterator.
	 * 
	 * @param iter
	 *        The underlying iterator, must not be <tt>null</tt>.
	 * @param limit
	 *        The number of query answers to return, must be larger than 0.
	 */
	public LimitIterator(Iterator<? extends E> iter, int limit) {
		super(iter);

		assert limit >= 0;

		this.limit = limit;
		this.returnCount = 0;
	}

	@Override
	public boolean hasNext() {
		return returnCount < limit && super.hasNext();
	}

	@Override
	public E next() {
		if (returnCount >= limit) {
			throw new NoSuchElementException("limit reached");
		}

		returnCount++;
		return super.next();
	}
}
